﻿#include "intercom.h"
#include <QJsonObject>
#include <QJsonDocument>

Intercom::Intercom(int port, QObject *parent) :
    QObject(parent),
    m_server(),
    m_cfg(),
    m_cliMap()
{
    m_server.listen(QHostAddress::Any, port);
    connect(&m_server, SIGNAL(newConnection()), this, SLOT(onNewConnection()));
}

void Intercom::onNewConnection()
{
    QTcpSocket *newSock = m_server.nextPendingConnection();

    WARNING_PRINT << "new connection from intercom.............";
    m_cliMap[newSock] = QString("");
    connect(newSock, SIGNAL(error(QAbstractSocket::SocketError)), this, SLOT(onClose(QAbstractSocket::SocketError)));
    connect(newSock, SIGNAL(readyRead()), this, SLOT(onRead()));

    QJsonObject jsonObj;
    QJsonDocument jsonDoc;

    jsonObj["id"] = OPEN_ID_REQUIRE_MAC;
    jsonDoc.setObject(jsonObj);
    newSock->write(jsonDoc.toJson(QJsonDocument::Compact));
}

void Intercom::onClose(QAbstractSocket::SocketError)
{
    QTcpSocket *sock = (QTcpSocket *)this->sender();
    WARNING_PRINT << "Intercom::onClose..... ";
    m_cliMap.remove(sock);
    sock->deleteLater();
}

void Intercom::onRead()
{
    QTcpSocket *sock = (QTcpSocket *)this->sender();
    QByteArray data = sock->readAll();
    QJsonParseError jsonErr;
    QJsonObject jsonObj;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(data, &jsonErr);

    if (jsonErr.error != QJsonParseError::NoError && !jsonDoc.isObject())
    {
        WARNING_PRINT << "recv unkown msg" << data << jsonErr.error;
        return ;
    }

    jsonObj = jsonDoc.object();
    //add areaid
    QJsonObject resultjson;
    resultjson.insert("id", jsonObj["id"].toInt());
    resultjson.insert("areaid", m_cfg.m_cfg.general.proxyId);
    resultjson.insert("userid", jsonObj["userid"]);
    resultjson.insert("openMode", jsonObj["openMode"]);
    resultjson.insert("mac",  m_cliMap[sock]);
    resultjson.insert("opentime",  CommonFuc::getCurTime());
    QJsonDocument document;
    document.setObject(resultjson);
    //resultData为发给网页后台的信息
    QByteArray resultData = document.toJson(QJsonDocument::Compact);

    emit textRecv(data);
    DEBUG_PRINT << "recv msg from intercom:" << data <<"---------"<<resultData;
    switch (jsonObj["id"].toInt())
    {
        case OPEN_ID_REPLY_OPENED:
        case OPEN_ID_REPLY_CLOSED:
        case OPEN_ID_REPLY_ALARM:
        case OPEN_ID_REPLY_ALARM_OVER:
            break;
        case OPEN_ID_REPLY_MAC:
            m_cliMap[sock] = jsonObj["mac"].toString();
            break;
        case HEARTBEAT_ID:
            sock->write(data);
            break;
        default:
            WARNING_PRINT << "recv unknown id" << jsonObj["id"].toInt();
            break;
    } 
    if(jsonObj["id"].toInt() != OPEN_ID_REPLY_OPENED) return;
    switch (jsonObj["openMode"].toInt())
    {
        case OPEN_MODE_ACCESS_CARD: //刷卡开门
        case OPEN_MODE_PASSWD: //密码开门
        case OPEN_MODE_REMOTE: //访客呼叫&&远程开门
        case OPEN_MODE_MANAGER: //一键呼叫管理处
        case OPEN_MODE_APP: //手机APP
        case OPEN_MODE_FACE: //人脸识别
        case OPEN_MODE_IDCARD: //身份证识别
        case OPEN_MODE_FINGERPRINT: //指纹识别
        case OPEN_MODE_WECHAT: //微信开门
        case OPEN_MODE_BUTTON: //按键开门
            DEBUG_PRINT << "open door ------: "<<jsonObj["openMode"].toInt()<<resultData;
            emit sigOpenDoor(resultData,m_cliMap[sock]);
    }
}

void Intercom::onFaceOpenDoor(QString mac, QString userid)
{
    emit textRecv(mac);
    QList<QTcpSocket *> keys = m_cliMap.keys(mac);
    for (int i = 0; i < keys.size(); i++)
    {
        QJsonObject jsonObj;
        QJsonDocument jsonDoc;
        jsonObj["id"] = OPEN_ID_REQUIRE_OPEN;
        jsonObj["openMode"] = OPEN_MODE_FACE;
        jsonObj["userid"] = userid;
        jsonDoc.setObject(jsonObj);
        keys.at(i)->write(jsonDoc.toJson(QJsonDocument::Compact));
        emit textRecv(QString("%1").arg(i));
    }
}

